package saxena.mf.db.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import saxena.mf.utils.MFQueries;

public class QueryHelper {

	private static QueryHelper helper = null;
	private Connection con = null;

	public static QueryHelper getHelper() throws ClassNotFoundException, SQLException {
		if (helper == null) {
			helper = new QueryHelper();
		}
		return helper;
	}

	private QueryHelper() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");

		String url = "jdbc:mysql://localhost:3306/mfdebug";
		con = DriverManager.getConnection(url, "root", "root");
	}
	
	public ResultSet executeQuery(String sql) throws SQLException{
		ResultSet resultSet = con.createStatement().executeQuery(sql);
		return resultSet;
	}
	
	public int executeUpdate(MFQueries query, String...args) throws Exception{
		PreparedStatement pstmt = con.prepareStatement(query.getSqlQuery());
		for(int i=0;i<query.getTypes().length;i++){
			switch (query.getTypes()[i]) {
			case CHAR:
			case VARCHAR:
				pstmt.setString(i+1, args[i]);
				break;
			
			case INT:
				pstmt.setInt(i+1, Integer.parseInt(args[i]));

			default:
				break;
			}
		}

		int count = pstmt.executeUpdate();
		
		return count;
	}
	
	public ResultSet executeQuery(MFQueries query, String...args) throws SQLException{
		PreparedStatement pstmt = con.prepareStatement(query.getSqlQuery());
		for(int i=0;i<query.getTypes().length;i++){
			switch (query.getTypes()[i]) {
			case CHAR:
			case VARCHAR:
				pstmt.setString(i+1, args[i]);
				break;
			
			case INT:
				pstmt.setInt(i+1, Integer.parseInt(args[i]));

			default:
				break;
			}
		}
		ResultSet res = pstmt.executeQuery();
		return res;
	}
	public static void main(String args[]) throws ClassNotFoundException, SQLException{
		QueryHelper helper = getHelper();
		ResultSet res = helper.executeQuery("select * from user");
		while(res.next()){
			System.out.println(res.getString(1)+"\t"+res.getString(2));
		}
	}
}
